package com.example.remotecontrol.util

import android.content.Context
import android.hardware.ConsumerIrManager
import android.os.Build
import android.util.Log
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 红外管理器
 * 负责处理红外信号的发送和管理
 */
@Singleton
class IRManager @Inject constructor(
    private val context: Context
) {
    private val TAG = "IRManager"
    
    // 获取系统红外服务
    private val irManager: ConsumerIrManager? by lazy {
        try {
            context.getSystemService(Context.CONSUMER_IR_SERVICE) as? ConsumerIrManager
        } catch (e: Exception) {
            Log.e(TAG, "IR service not available: ${e.message}")
            null
        }
    }
    
    /**
     * 检查设备是否支持红外功能
     */
    fun hasIrEmitter(): Boolean {
        return irManager?.hasIrEmitter() ?: false
    }
    
    /**
     * 获取设备支持的红外频率范围
     */
    fun getCarrierFrequencies(): Array<ConsumerIrManager.CarrierFrequencyRange>? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                irManager?.carrierFrequencies
            } catch (e: Exception) {
                Log.e(TAG, "Failed to get carrier frequencies: ${e.message}")
                null
            }
        } else {
            null
        }
    }
    
    /**
     * 检查指定频率是否在设备支持范围内
     */
    fun isFrequencySupported(frequency: Int): Boolean {
        val ranges = getCarrierFrequencies() ?: return false
        
        for (range in ranges) {
            if (frequency in range.minFrequency..range.maxFrequency) {
                return true
            }
        }
        return false
    }
    
    /**
     * 发送红外信号
     * @param frequency 红外频率（Hz）
     * @param pattern 红外码，包含脉冲持续时间（微秒）
     */
    fun transmit(frequency: Int, pattern: IntArray): Boolean {
        return try {
            irManager?.transmit(frequency, pattern)
            true
        } catch (e: Exception) {
            Log.e(TAG, "Failed to transmit IR signal: ${e.message}")
            false
        }
    }
    
    /**
     * 发送NEC格式的红外信号
     * @param address 设备地址码
     * @param command 命令码
     */
    fun transmitNEC(address: Int, command: Int): Boolean {
        // NEC协议使用38kHz的载波频率
        val frequency = 38000
        
        // 生成NEC格式的红外码
        val pattern = generateNECPattern(address, command)
        
        return transmit(frequency, pattern)
    }
    
    /**
     * 发送红外命令（给IRController使用）
     * @param address 设备地址码
     * @param command 命令码
     * @return 是否发送成功
     */
    fun transmitIrCommand(address: Int, command: Int): Boolean {
        return transmitNEC(address, command)
    }
    
    /**
     * 生成NEC格式的红外码
     * NEC格式:
     * - 引导码: 9ms脉冲 + 4.5ms空闲
     * - 地址码(8位) + 地址码反码(8位)
     * - 命令码(8位) + 命令码反码(8位)
     * - 结束位: 562.5μs脉冲
     */
    private fun generateNECPattern(address: Int, command: Int): IntArray {
        // NEC时序参数（微秒）
        val leadPulse = 9000    // 引导码脉冲
        val leadSpace = 4500    // 引导码空闲
        val bit1Pulse = 560     // 1位脉冲
        val bit1Space = 1690    // 1位空闲
        val bit0Pulse = 560     // 0位脉冲
        val bit0Space = 560     // 0位空闲
        val stopPulse = 560     // 结束位脉冲
        
        // 计算总位数：引导码(2) + 地址(16) + 命令(16) + 结束位(1) = 35
        val pattern = IntArray(35 * 2)
        var index = 0
        
        // 添加引导码
        pattern[index++] = leadPulse
        pattern[index++] = leadSpace
        
        // 添加地址码 (8位)
        for (i in 0 until 8) {
            pattern[index++] = bit1Pulse
            pattern[index++] = if (((address shr i) and 1) == 1) bit1Space else bit0Space
        }
        
        // 添加地址码反码 (8位)
        for (i in 0 until 8) {
            pattern[index++] = bit1Pulse
            pattern[index++] = if (((address shr i) and 1) == 0) bit1Space else bit0Space
        }
        
        // 添加命令码 (8位)
        for (i in 0 until 8) {
            pattern[index++] = bit1Pulse
            pattern[index++] = if (((command shr i) and 1) == 1) bit1Space else bit0Space
        }
        
        // 添加命令码反码 (8位)
        for (i in 0 until 8) {
            pattern[index++] = bit1Pulse
            pattern[index++] = if (((command shr i) and 1) == 0) bit1Space else bit0Space
        }
        
        // 添加结束位
        pattern[index++] = stopPulse
        pattern[index++] = 0  // 空闲时间为0，表示结束
        
        return pattern
    }
} 